# backend/crud/book_crud.py
from sqlalchemy.orm import Session
from backend.models import Book


def create_book(db: Session, isbn: str, title: str, author: str, cover_url: str,
                library_id: int, added_by: int):
    db_book = Book(
        isbn=isbn,
        title=title,
        author=author,
        cover_url=cover_url,
        library_id=library_id,
        added_by=added_by,
        added_at=datetime.utcnow(),
        status=1  # 默认上架
    )
    db.add(db_book)
    db.commit()
    db.refresh(db_book)
    return db_book


def get_book(db: Session, book_id: int):
    return db.query(Book).filter(Book.id == book_id).first()


def update_book_status(db: Session, book_id: int, status: int):
    db_book = get_book(db, book_id)
    if db_book:
        db_book.status = status
        db.commit()
        db.refresh(db_book)
    return db_book


def search_books(db: Session, library_id: int, query: str):
    return db.query(Book).filter(
        Book.library_id == library_id,
        Book.status == 1,  # 只搜索上架图书
        (Book.title.ilike(f"%{query}%") | Book.author.ilike(f"%{query}%"))
    ).all()
